package org.jeecg.modules.online.config.p022d;

import com.alibaba.druid.filter.config.ConfigTools;
import com.baomidou.mybatisplus.annotation.DbType;
import freemarker.template.TemplateException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.jeecg.common.util.SqlInjectionUtil;
import org.jeecg.common.util.dynamic.db.DbTypeUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.utils.CgformUtil;
import org.jeecg.modules.online.config.exception.DBException;
import org.jeecg.modules.online.config.p020b.CgformConfigModel;
import org.jeecg.modules.online.config.p020b.DataBaseConfig;
import org.jeecg.modules.online.config.service.DbTableHandleI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* renamed from: org.jeecg.modules.online.config.d.c */
/* loaded from: hibernate-re-3.7.1-RC.jar:org/jeecg/modules/online/config/d/c.class */
public class DbTableProcess {

    /* renamed from: b */
    private static final String f584b = "org/jeecg/modules/online/config/engine/tableTemplate.ftl";

    /* renamed from: c */
    private static DbTableHandleI f585c;

    /* renamed from: a */
    private static final Logger f583a = LoggerFactory.getLogger(DbTableProcess.class);

    /* renamed from: d */
    private static ServiceRegistry f586d = null;

    public DbTableProcess(DataBaseConfig dataBaseConfig) throws SQLException, DBException {
        f585c = DbTableUtil.m32a(dataBaseConfig);
    }

    public DbTableProcess() throws SQLException, DBException {
        f585c = DbTableUtil.m32a((DataBaseConfig) null);
    }

    /* renamed from: a */
    public static void m53a(CgformConfigModel cgformConfigModel) throws IOException, TemplateException, HibernateException, SQLException, DBException {
        String message;
        DbType m27c = DbTableUtil.m27c(cgformConfigModel.getDbConfig());
        if (DbTypeUtils.dbTypeIsOracle(m27c)) {
            ArrayList arrayList = new ArrayList();
            for (OnlCgformField onlCgformField : cgformConfigModel.getColumns()) {
                if ("int".equals(onlCgformField.getDbType())) {
                    onlCgformField.setDbType("double");
                    onlCgformField.setDbPointLength(0);
                }
                arrayList.add(onlCgformField);
            }
            cgformConfigModel.setColumns(arrayList);
        }
        String m22a = FreemarkerHelper.m22a(f584b, m52a(cgformConfigModel, m27c));
        f583a.debug("xml：{}", m22a);
        HashMap hashMap = new HashMap(5);
        DataBaseConfig dbConfig = cgformConfigModel.getDbConfig();
        if (f586d == null) {
            hashMap.put("hibernate.connection.driver_class", dbConfig.getDriverClassName());
            hashMap.put("hibernate.connection.url", dbConfig.getUrl());
            hashMap.put("hibernate.connection.username", dbConfig.getUsername());
            String password = dbConfig.getPassword();
            if (password != null) {
                if (dbConfig.getDruid() != null && oConvertUtils.isNotEmpty(dbConfig.getDruid().getPublicKey())) {
                    try {
                        hashMap.put("hibernate.connection.password", ConfigTools.decrypt(dbConfig.getDruid().getPublicKey(), password));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    hashMap.put("hibernate.connection.password", password);
                }
            }
            hashMap.put("hibernate.show_sql", true);
            hashMap.put("hibernate.format_sql", true);
            hashMap.put("hibernate.temp.use_jdbc_metadata_defaults", false);
            hashMap.put("hibernate.dialect", DbTypeUtils.getDbDialect(m27c));
            hashMap.put("hibernate.hbm2ddl.auto", "create");
            hashMap.put("hibernate.connection.autocommit", false);
            hashMap.put("hibernate.current_session_context_class", "thread");
            f586d = new StandardServiceRegistryBuilder().applySettings(hashMap).build();
        }
        MetadataSources metadataSources = new MetadataSources(f586d);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(m22a.getBytes("utf-8"));
        metadataSources.addInputStream(byteArrayInputStream);
        Metadata buildMetadata = metadataSources.buildMetadata();
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.create(EnumSet.of(TargetType.DATABASE), buildMetadata);
        byteArrayInputStream.close();
        List<Exception> exceptions = schemaExport.getExceptions();
        for (Exception exc : exceptions) {
            if ("java.sql.SQLSyntaxErrorException".equals(exc.getCause().getClass().getName())) {
                SQLSyntaxErrorException sQLSyntaxErrorException = (SQLSyntaxErrorException) exc.getCause();
                if ("42000".equals(sQLSyntaxErrorException.getSQLState())) {
                    if (1064 == sQLSyntaxErrorException.getErrorCode() || 903 == sQLSyntaxErrorException.getErrorCode()) {
                        f583a.error(sQLSyntaxErrorException.getMessage());
                        throw new DBException("请确认表名是否为关键字。");
                    }
                } else {
                    throw new DBException(exc.getMessage());
                }
            } else if ("com.microsoft.sqlserver.jdbc.SQLServerException".equals(exc.getCause().getClass().getName())) {
                if (exc.getCause().toString().indexOf("Incorrect syntax near the keyword") != -1) {
                    exc.printStackTrace();
                    throw new DBException(exc.getCause().getMessage());
                }
                f583a.error(exc.getMessage());
            } else {
                if ((DbType.DM.equals(m27c) || DbType.DB2.equals(m27c)) && (message = exc.getMessage()) != null && message.indexOf("Error executing DDL \"drop table") >= 0) {
                    f583a.error(message);
                }
                throw new DBException(exc.getMessage());
            }
        }
    }

    /* renamed from: b */
    public List<String> m46b(CgformConfigModel cgformConfigModel) throws DBException, SQLException {
        DbType m27c = DbTableUtil.m27c(cgformConfigModel.getDbConfig());
        String m37a = DbTableUtil.m37a(cgformConfigModel.getTableName(), DbTypeUtils.getDbTypeString(m27c));
        String str = "alter table  " + m37a + " ";
        List<String> arrayList = new ArrayList<>();
        try {
            Map<String, ColumnMeta> m55a = m55a((String) null, m37a, cgformConfigModel.getDbConfig());
            Map<String, ColumnMeta> m41c = m41c(cgformConfigModel);
            Map<String, String> m54a = m54a(cgformConfigModel.getColumns());
            for (String str2 : m41c.keySet()) {
                if (!"id".equalsIgnoreCase(str2)) {
                    if (!m55a.containsKey(str2)) {
                        ColumnMeta columnMeta = m41c.get(str2);
                        String str3 = m54a.get(str2);
                        if (m54a.containsKey(str2) && m55a.containsKey(str3)) {
                            ColumnMeta columnMeta2 = m55a.get(str3);
                            if (DbType.HSQL.equals(m27c)) {
                                m49a(columnMeta2, columnMeta, m37a, arrayList);
                            } else {
                                String reNameFieldName = f585c.getReNameFieldName(columnMeta);
                                if (DbTypeUtils.dbTypeIsSqlServer(m27c)) {
                                    arrayList.add(reNameFieldName);
                                } else {
                                    arrayList.add(str + reNameFieldName);
                                }
                                m55a.put(str2, m55a.remove(str3));
                                if (DbType.DB2.equals(m27c)) {
                                    m49a(columnMeta2, columnMeta, m37a, arrayList);
                                } else {
                                    if (!columnMeta2.equals(columnMeta)) {
                                        arrayList.add(str + m50a(columnMeta, columnMeta2));
                                        if (DbTypeUtils.dbTypeIsPostgre(m27c)) {
                                            String m44b = m44b(columnMeta, columnMeta2);
                                            if (oConvertUtils.isNotEmpty(m44b)) {
                                                arrayList.add(str + m44b);
                                            }
                                        }
                                    }
                                    if (!DbTypeUtils.dbTypeIsSqlServer(m27c) && !columnMeta2.m59b(columnMeta)) {
                                        arrayList.add(m40c(columnMeta));
                                    }
                                }
                            }
                            arrayList.add(m42c(str2, columnMeta.getColumnId()));
                        } else {
                            arrayList.add(str + m45b(columnMeta));
                            if (!DbTypeUtils.dbTypeIsSqlServer(m27c) && StringUtils.isNotEmpty(columnMeta.getComment())) {
                                arrayList.add(m40c(columnMeta));
                            }
                        }
                    } else {
                        ColumnMeta columnMeta3 = m55a.get(str2);
                        ColumnMeta columnMeta4 = m41c.get(str2);
                        if (DbType.DB2.equals(m27c) || DbType.HSQL.equals(m27c)) {
                            m49a(columnMeta3, columnMeta4, m37a, arrayList);
                        } else {
                            if (!columnMeta3.m62a(columnMeta4, m27c)) {
                                arrayList.add(str + m50a(columnMeta4, columnMeta3));
                            }
                            if (!DbTypeUtils.dbTypeIsSqlServer(m27c) && !DbTypeUtils.dbTypeIsOracle(m27c) && !columnMeta3.m59b(columnMeta4)) {
                                arrayList.add(m40c(columnMeta4));
                            }
                        }
                    }
                }
            }
            for (String str4 : m55a.keySet()) {
                if (!m41c.containsKey(str4.toLowerCase()) && !m54a.containsValue(str4.toLowerCase())) {
                    arrayList.add(str + m48b(str4));
                }
            }
            if (DbType.DB2.equals(m27c)) {
                arrayList.add("CALL SYSPROC.ADMIN_CMD('reorg table " + m37a + "')");
            }
            return arrayList;
        } catch (SQLException e) {
            throw new RuntimeException();
        }
    }

    /* renamed from: a */
    private static Map<String, Object> m52a(CgformConfigModel cgformConfigModel, DbType dbType) {
        String dbTypeString = DbTypeUtils.getDbTypeString(dbType);
        HashMap hashMap = new HashMap(5);
        for (OnlCgformField onlCgformField : cgformConfigModel.getColumns()) {
            onlCgformField.setDbDefaultVal(m43c(onlCgformField.getDbDefaultVal()));
        }
        hashMap.put("entity", cgformConfigModel);
        hashMap.put("dataType", dbTypeString);
        hashMap.put("db", dbType.getDb());
        return hashMap;
    }

    /* renamed from: a */
    private Map<String, ColumnMeta> m55a(String str, String str2, DataBaseConfig dataBaseConfig) throws SQLException {
        ResultSet columns;
        HashMap hashMap = new HashMap(5);
        Connection connection = null;
        try {
            connection = DbTableUtil.m29b(dataBaseConfig);
        } catch (Exception e) {
            f583a.error(e.getMessage(), e);
        }
        DatabaseMetaData metaData = connection.getMetaData();
        String username = dataBaseConfig.getUsername();
        DbType m27c = DbTableUtil.m27c(dataBaseConfig);
        if (DbTypeUtils.dbTypeIsOracle(m27c) || DbType.DB2.equals(m27c)) {
            username = username.toUpperCase();
        }
        if (DbTypeUtils.dbTypeIsSqlServer(m27c)) {
            columns = metaData.getColumns(connection.getCatalog(), null, str2, "%");
        } else if (DbTypeUtils.dbTypeIsPostgre(m27c)) {
            columns = metaData.getColumns(connection.getCatalog(), DbTableUtil.m30b(connection), str2, "%");
        } else if (DbType.HSQL.equals(m27c)) {
            columns = metaData.getColumns(connection.getCatalog(), "PUBLIC", str2.toUpperCase(), "%");
        } else {
            columns = metaData.getColumns(connection.getCatalog(), username, str2, "%");
        }
        while (columns.next()) {
            ColumnMeta columnMeta = new ColumnMeta();
            columnMeta.setTableName(str2);
            String lowerCase = columns.getString("COLUMN_NAME").toLowerCase();
            columnMeta.setColumnName(lowerCase);
            String string = columns.getString("TYPE_NAME");
            int i = columns.getInt("DECIMAL_DIGITS");
            columnMeta.setColunmType(f585c.getMatchClassTypeByDataType(string, i));
            columnMeta.setRealDbType(string);
            int i2 = columns.getInt("COLUMN_SIZE");
            columnMeta.setColumnSize(i2);
            columnMeta.setDecimalDigits(i);
            columnMeta.setIsNullable(columns.getInt("NULLABLE") == 1 ? "Y" : "N");
            columnMeta.setComment(columns.getString("REMARKS"));
            String string2 = columns.getString("COLUMN_DEF");
            columnMeta.setFieldDefault(m43c(string2) == null ? "" : m43c(string2));
            f583a.debug("getColumnMetadataFormDataBase --->COLUMN_NAME:" + lowerCase.toUpperCase() + " TYPE_NAME :" + string + " DECIMAL_DIGITS:" + i + " COLUMN_SIZE:" + i2);
            hashMap.put(lowerCase, columnMeta);
        }
        return hashMap;
    }

    /* renamed from: c */
    private Map<String, ColumnMeta> m41c(CgformConfigModel cgformConfigModel) {
        HashMap hashMap = new HashMap(5);
        for (OnlCgformField onlCgformField : cgformConfigModel.getColumns()) {
            ColumnMeta columnMeta = new ColumnMeta();
            columnMeta.setTableName(cgformConfigModel.getTableName().toLowerCase());
            columnMeta.setColumnId(onlCgformField.getId());
            columnMeta.setColumnName(onlCgformField.getDbFieldName().toLowerCase());
            columnMeta.setColumnSize(onlCgformField.getDbLength().intValue());
            columnMeta.setColunmType(onlCgformField.getDbType().toLowerCase());
            columnMeta.setIsNullable(onlCgformField.getDbIsNull().intValue() == 1 ? "Y" : "N");
            columnMeta.setComment(onlCgformField.getDbFieldTxt());
            columnMeta.setDecimalDigits(onlCgformField.getDbPointLength().intValue());
            columnMeta.setFieldDefault(m43c(onlCgformField.getDbDefaultVal()));
            columnMeta.setPkType(cgformConfigModel.getJformPkType() == null ? "UUID" : cgformConfigModel.getJformPkType());
            columnMeta.setOldColumnName(onlCgformField.getDbFieldNameOld() != null ? onlCgformField.getDbFieldNameOld().toLowerCase() : null);
            f583a.debug("getColumnMetadataFormCgForm ----> DbFieldName: " + onlCgformField.getDbFieldName().toLowerCase() + " | DbType: " + onlCgformField.getDbType().toLowerCase() + " | DbPointLength:" + onlCgformField.getDbPointLength() + " | DbLength:" + onlCgformField.getDbLength());
            hashMap.put(onlCgformField.getDbFieldName().toLowerCase(), columnMeta);
        }
        return hashMap;
    }

    /* renamed from: a */
    private Map<String, String> m54a(List<OnlCgformField> list) {
        HashMap hashMap = new HashMap(5);
        for (OnlCgformField onlCgformField : list) {
            hashMap.put(onlCgformField.getDbFieldName(), onlCgformField.getDbFieldNameOld());
        }
        return hashMap;
    }

    /* renamed from: b */
    private String m48b(String str) {
        return f585c.getDropColumnSql(str);
    }

    /* renamed from: a */
    private String m50a(ColumnMeta columnMeta, ColumnMeta columnMeta2) throws DBException {
        return f585c.getUpdateColumnSql(columnMeta, columnMeta2);
    }

    /* renamed from: b */
    private String m44b(ColumnMeta columnMeta, ColumnMeta columnMeta2) {
        return f585c.getSpecialHandle(columnMeta, columnMeta2);
    }

    /* renamed from: a */
    private void m49a(ColumnMeta columnMeta, ColumnMeta columnMeta2, String str, List<String> list) {
        f585c.handleUpdateMultiSql(columnMeta, columnMeta2, str, list);
    }

    /* renamed from: a */
    private String m51a(ColumnMeta columnMeta) {
        return f585c.getReNameFieldName(columnMeta);
    }

    /* renamed from: b */
    private String m45b(ColumnMeta columnMeta) {
        return f585c.getAddColumnSql(columnMeta);
    }

    /* renamed from: c */
    private String m40c(ColumnMeta columnMeta) {
        return f585c.getCommentSql(columnMeta);
    }

    /* renamed from: c */
    private String m42c(String str, String str2) {
        return "update onl_cgform_field set DB_FIELD_NAME_OLD = '" + str + "' where ID ='" + str2 + CgformUtil.f231C;
    }

    /* renamed from: a */
    private int m56a(String str, String str2, Session session) {
        return session.createSQLQuery("update onl_cgform_field set DB_FIELD_NAME_OLD= '" + str + "' where ID ='" + str2 + CgformUtil.f231C).executeUpdate();
    }

    /* renamed from: c */
    private static String m43c(String str) {
        if (StringUtils.isNotEmpty(str)) {
            try {
                Double.valueOf(str);
            } catch (Exception e) {
                if (!str.startsWith(CgformUtil.f231C) || !str.endsWith(CgformUtil.f231C)) {
                    str = CgformUtil.f231C + str + CgformUtil.f231C;
                }
            }
        }
        return str;
    }

    /* renamed from: a */
    public String m57a(String str, String str2) {
        return f585c.dropIndexs(SqlInjectionUtil.getSqlInjectField(str), SqlInjectionUtil.getSqlInjectTableName(str2));
    }

    /* renamed from: b */
    public String m47b(String str, String str2) {
        return f585c.countIndex(SqlInjectionUtil.getSqlInjectField(str), SqlInjectionUtil.getSqlInjectTableName(str2));
    }

    /* renamed from: a */
    public static List<String> m58a(String str) throws SQLException {
        Connection connection = null;
        ArrayList arrayList = new ArrayList();
        try {
            try {
                connection = DbTableUtil.getConnection();
                ResultSet indexInfo = connection.getMetaData().getIndexInfo(null, null, str, false, false);
                indexInfo.getMetaData();
                while (indexInfo.next()) {
                    String string = indexInfo.getString("INDEX_NAME");
                    if (oConvertUtils.isEmpty(string)) {
                        string = indexInfo.getString("index_name");
                    }
                    if (oConvertUtils.isNotEmpty(string)) {
                        arrayList.add(string);
                    }
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                f583a.error(e.getMessage(), e);
                if (connection != null) {
                    connection.close();
                }
            }
            return arrayList;
        } catch (Throwable th) {
            if (connection != null) {
                connection.close();
            }
            throw th;
        }
    }
}
